package com.hadoop.mr.pagerank;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Arrays;

/**
 * <p></p>
 *
 * @author Andy
 * @date 2017/10/26
 */
public class Node {

    //A  0.25  B  D
    //B  0.25  C
    //C  0.25  A  B
   //D  0.25  B  C

    private double pageRank = 0.25;
    private String[] adjacentNodeNames;

    public static final char FIELDSEPARATOR = '\t';

    public double getPageRank() {
        return pageRank;
    }

    public Node setPageRank(double pageRank) {
        this.pageRank = pageRank;
        return this;
    }

    public String[] getAdjacentNodeNames() {
        return adjacentNodeNames;
    }

    public Node setAdjacentNodeNames(String[] adjacentNodeNames) {
        this.adjacentNodeNames = adjacentNodeNames;
        return this;
    }

    public boolean containsAdjacentNodes() {
        return this.adjacentNodeNames != null;
    }

    @Override
    public String toString() {
        StringBuilder mapInVal = new StringBuilder();
        mapInVal.append(pageRank);
        if (getAdjacentNodeNames() != null) {
            mapInVal.append(FIELDSEPARATOR).append(StringUtils.join(getAdjacentNodeNames(), FIELDSEPARATOR));
        }
        return mapInVal.toString();
    }

    /**
     * 拆分并且重新组装Node如：key=A  value="0.25  B  D"的数据
     * @param value
     * @return
     * @throws IOException
     */
    public static Node fromMr(String value) throws IOException {
        String[] parts = StringUtils.splitPreserveAllTokens(value, FIELDSEPARATOR);
        if (parts.length < 1) {
            throw new IOException("Expected 1 or more parts but received " + parts.length);
        }

        Node node = new Node().setPageRank(Double.valueOf(parts[0]));
        if (parts.length > 1) {
            node.setAdjacentNodeNames(Arrays.copyOfRange(parts, 1, parts.length));
        }
        return node;
    }
}
